from rest_framework.views import APIView
from .serializers import UploadImageSerializer
from rest_framework.response import Response
from shortuuid import uuid
import os
from django.conf import settings

class UploadImageView(APIView):
    def post(self, request):
        #1.校验图片格式是否正确
        #2.不接收一些格式的文件
        serializer = UploadImageSerializer(data=request.data) #序列化验证
        if serializer.is_valid():
            file = serializer.validated_data.get('image') #获取验证过的图片
            #abc.png => dsdqqrqe.png
            #os.path.splitext('abc.png') =>('abc','.png')
            filename = uuid() + os.path.splitext(file.name)[-1]
            path = settings.MEDIA_ROOT / filename #存放路径
            try:
                with open(path, 'wb') as fp:
                    for chunk in file.chunks():
                        fp.write(chunk)
            except Exception as e:
                return Response({
                    'error':1,
                    'message':'图片保存失败！'
                })
            #abc.png => /media/abc.png
            file_url = settings.MEDIA_URL + filename
            return Response({  #wangeditor的格式要求
                "errno": 0, # 注意：值是数字，不能是字符串
                "data": {
                    "url": file_url, # 图片 src ，必须
                    "alt": "", # 图片描述文字，非必须
                    "href": file_url # 图片的链接，非必须
    }
})
        else:
            print(serializer.errors)
            return Response({  #wangeditor的要求
                "errno": 1, #只要不等于 0 就行
                "message": list(serializer.errors .values())[0][0]
            #{'image': [ErrorDetail(string='图片最大不能超过0.5MB!', code='invalid')]}
            })